//
//  YBCloudComputerProgressCell.swift
//  Moonlight
//
//  Created by 清风徐来 on 2023/7/3.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift

class YBCloudComputerProgressCell: UITableViewCell {
    
    // 当前进度
    enum ProgressType {
        case progressing
        case done
        case fail
    }
    
    var powerOnBlock: (() -> Void)?
    var powerOffBlock: (() -> Void)?
    var reTryBlock: (() -> Void)?
    
    private var internalProgress: ProgressType = .progressing // 内部状态

    var progress: ProgressType {
        set {
            internalProgress = newValue // 更新内部
            DispatchQueue.main.async {
                switch newValue {
                case .progressing:
                    self.titleLabel.text = "开机中..."
                    self.titleLabel.isHidden = false
                    self.bkimgView.isHidden  = false
                    self.primgView.isHidden = false
                    
                    self.reTryBtn.isHidden = true
                    self.toComputerBtn.isHidden = true
                    self.powerOffBtn.isHidden = true
                    break
                    
                case .done:
                    self.titleLabel.isHidden = true
                    self.bkimgView.isHidden  = true
                    self.primgView.isHidden = true
                    
                    self.reTryBtn.isHidden = true
                    self.toComputerBtn.isHidden = false
                    self.powerOffBtn.isHidden = false
                    break
                    
                case .fail:
                    self.titleLabel.text = "开机失败，请重试"
                    self.titleLabel.isHidden = false
                    self.bkimgView.isHidden  = true
                    self.primgView.isHidden = true
                    
                    self.reTryBtn.isHidden = false
                    self.toComputerBtn.isHidden = true
                    self.powerOffBtn.isHidden = true
                    break
                }
            }

            // 隐藏菊花圈
            stopRefreshProgress()
        }
        get {
            return internalProgress
        }
    }
    
    // 定义 primgView 宽度约束
    var primgViewWidthConstraint: Constraint?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        contentView.addSubviews([titleLabel, bkimgView, primgView, powerOffBtn, toComputerBtn, reTryBtn])
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(8)
            make.height.equalTo(16)
        }
        
        bkimgView.snp.makeConstraints { make in
            make.bottom.equalTo(-12)
            make.left.equalTo(20)
            make.centerX.equalToSuperview()
            make.height.equalTo(UIDevice.bk_isiPhone ? 16 : 32)
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
        }
        
        // 在布局代码中，使用 SnapKit 进行 bkimgView 的约束设置
        primgView.snp.makeConstraints { make in
            primgViewWidthConstraint = make.width.equalTo(0).constraint
            // 其他约束设置
            make.centerY.left.height.equalTo(bkimgView)
        }
        
        powerOffBtn.snp.makeConstraints { make in
            make.top.equalTo(15)
            make.left.equalTo(20)
            make.size.equalTo(CGSizeMake((kScreenWidth - 60) / 2, 40))
        }
        
        toComputerBtn.snp.makeConstraints { make in
            make.top.equalTo(powerOffBtn)
            make.bottom.equalTo(powerOffBtn)
            make.left.equalTo(powerOffBtn.snp.right).offset(20)
            make.size.equalTo(powerOffBtn)
        }
        
        reTryBtn.snp.makeConstraints { make in
            make.top.equalTo(bkimgView)
            make.height.equalTo(30)
            make.width.equalTo(powerOffBtn)
            make.centerX.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - lazy
    private lazy var titleLabel = self.bk_addLabel(text: "开机中...", font: .systemFont(ofSize: 15, weight: .semibold), bgColor: .clear, textColor: UIColor.hex("#2E8FFF"))
    
    private lazy var bkimgView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "icon_cloudcomputer_progressbg"))
        iv.contentMode = .scaleAspectFill
        iv.bk_cornerRadius = UIDevice.bk_isiPhone ? 8 : 16
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var primgView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "icon_cloudcomputer_progress"))
        iv.contentMode = .scaleAspectFill
        iv.bk_cornerRadius = UIDevice.bk_isiPhone ? 8 : 16
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var toComputerBtn: UIButton = {
        let btn = self.bk_addGradientButton(title: "进入", titleColor: .white, gradientSize: .init(width: (kScreenWidth - 60) / 2, height: 40), colors: [UIColor.hex("58B6FF"), UIColor.hex("#2880ED")], radius: 20)
        btn.isUserInteractionEnabled = true
        btn.isHidden = true
        btn.bk_addTarget { [self] button in
            button.showLoading()
            powerOnBlock?()
        }
        return btn
    }()
    
    private lazy var powerOffBtn: UIButton = {
        let btn = self.bk_addButton(title: "关机", bgColor: UIColor.hex("#C4DFFF"), titleColor: UIColor.hex("#2E8FFF"), radius: 20)
        btn.isUserInteractionEnabled = true
        btn.isHidden = true
        btn.bk_addTarget { [self] button in
            button.showLoading()
            powerOffBlock?()
        }
        return btn
    }()
    
    private lazy var reTryBtn: UIButton = {
        let btn = self.bk_addButton(title: "重试", bgColor: UIColor.hex("#C4DFFF"), titleColor: UIColor.hex("#2E8FFF"), radius: 15)
        btn.isUserInteractionEnabled = true
        btn.isHidden = true
        btn.bk_addTarget { [self] button in
            button.showLoading()
            reTryBlock?()
        }
        return btn
    }()

}

//MARK: - Action
extension YBCloudComputerProgressCell {
    
    // 更新进度
    func refreshProgress(progress: CGFloat) {
        if self.progress == .done || self.progress == .fail {
            return
        }

        let currentProgress = min(0.999, progress)
        let width = self.bkimgView.frame.width
        let current = width * currentProgress
         print(String(format: "开机中....%.2f %%", current / width * 100))

        DispatchQueue.main.async {
            self.primgViewWidthConstraint?.update(offset: current) 
            self.contentView.layoutIfNeeded() // 强制布局更新
        }
    }

    /// 刷新标题
    func refreshTitle(_ title: String) {
        DispatchQueue.main.async {
            self.titleLabel.text = title
        }
    }
    
    /// 停止刷新
   private func stopRefreshProgress() {
        self.toComputerBtn.hideLoading()
        self.powerOffBtn.hideLoading()
        self.reTryBtn.hideLoading()
    }
}
